﻿using EFMVC.AchieveInterface;
using EFMVC.Common;
using EFMVC.EDMX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace EFMVC.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Login()
        {
            FormsAuthentication.SignOut();
            TempData["ReturnUrl"] = Convert.ToString(Request["ReturnUrl"]);
            return View();
        }
        [HttpPost]
        public ActionResult Login(FormCollection fc)
        {
             EFMVC.Interface.IBaseReposity<Sys_User> sysUserReposty = new BaseReposity<Sys_User>(new TPYEntities1());
            string userName = fc["inputName"];
            string password = fc["inputPassword"];
            string halt = System.Configuration.ConfigurationManager.AppSettings["halt"];
            string PsswordByEncrypt = Encrypt.EncryptString(halt + password);
            bool rememberMe=fc["ckbRememberMe"]==null?false:true;
            string returnUrl = Convert.ToString(TempData["ReturnUrl"]);
            //验证用户
            Sys_User user = sysUserReposty.Get(filter: m => m.Name == userName && (m.Password == password || m.Password == PsswordByEncrypt))
                .FirstOrDefault();
            sysUserReposty.Dispose();
            //保存票据
            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(userName, rememberMe);
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return Redirect("~/");
                }
            }
            else {
                ViewBag.LoginState = "用户名或密码错误，请重试";
            }
            return View();
        }

        public ActionResult Logout()
        {
            CustomAuthorizeAttribute cou = new CustomAuthorizeAttribute();
            //cou.AuthorizeCore(this.HttpContext);
            FormsAuthentication.SignOut();
            return Redirect(Request.UrlReferrer.ToString());
        }
    }
}
